package com.blustreaksw.cyclecoach.history;

import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.UserProfileActivity;
import com.blustreaksw.cyclecoach.data.UserProfile.MeasurementUnits;
import com.blustreaksw.cyclecoach.util.ConfirmationDialogFragment;

public class WorkoutHistoryFragment extends ListFragment {
	
	private TextView mEmptyView;
	private static final String TAG = "WorkoutHistoryFragment";
	private static final double KM_TO_MILES = 0.621371;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
        setHasOptionsMenu(true);
        
        WorkoutHistoryContainer.getInstance(getActivity()).refreshContainer();
        setListAdapter(new WorkoutLogEntryAdapter(
    		WorkoutHistoryContainer.getInstance(getActivity()).getAllLogEntries()));
		((WorkoutLogEntryAdapter)getListAdapter()).notifyDataSetChanged();
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.list_empty, parent, false);
		mEmptyView = (TextView)v.findViewById(R.id.emptyView);
		mEmptyView.setText("No workout sessions logged");
		getActivity().setTitle(R.string.subactivity_workoutHistory_title);
		return v;
	}
	
	@Override
	public void onViewCreated(View v, Bundle savedInstanceState) {
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> av, View v, int position, long id) {
				
				final WorkoutLogEntry w = ((WorkoutLogEntryAdapter)getListAdapter()).getItem(position);
				new ConfirmationDialogFragment().configureDialog(new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Ok
						WorkoutHistoryContainer.getInstance(getActivity()).deleteLogEntry(w);
						((WorkoutLogEntryAdapter)getListAdapter()).notifyDataSetChanged();
					}
				}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Cancel
						
					}
				}, w.getDate().toString(), "Delete this workout?", getActivity())
				.onCreateDialog(null).show();
				
				return true;
			}
			
		});
	}
	
	public void onListItemClick(ListView l, View v, int position, long id) {
        // get the log entry from the adapter
        WorkoutLogEntry w = ((WorkoutLogEntryAdapter)getListAdapter()).getItem(position);
        if(w == null) {
        	Log.d(TAG, "onListItemClick getItem() returned null");
        }
        // start an instance of WorkoutLogEntryActionSwipeActivity
        Intent i = new Intent(getActivity(), WorkoutLogEntryActionSwipeActivity.class);
        i.putExtra(WorkoutLogEntryFragment.EXTRA_WORKOUT_ENTRY_ID, w.getId());
        startActivityForResult(i, 0);
    }
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	WorkoutHistoryContainer.getInstance(getActivity()).refreshContainer();
        ((WorkoutLogEntryAdapter)getListAdapter()).notifyDataSetChanged();
    }
    
    private class WorkoutLogEntryAdapter extends ArrayAdapter<WorkoutLogEntry> {
        public WorkoutLogEntryAdapter(ArrayList<WorkoutLogEntry> history) {
            super(getActivity(), android.R.layout.simple_list_item_1, history);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // if we weren't given a view, inflate one
            if (null == convertView) {
                convertView = getActivity().getLayoutInflater()
                    .inflate(R.layout.list_item_workout_log_entry, null);
            }

            // configure the view for this log entry
            WorkoutLogEntry w = getItem(position);
            
            if(w == null) {
            	Log.d(TAG, "getView - getItem() returned null");
            }

            TextView dateTextView =
                (TextView)convertView.findViewById(R.id.workoutLogEntryListItem_dateTextView);
            dateTextView.setText(w.getDate().toString());
            
            TextView timeElapsed =
                (TextView)convertView.findViewById(R.id.workoutLogEntryListItem_timeElapsedView);
            
            if(w.getTimeElapsed() >= 3600000) {
            	timeElapsed.setText(String.format("%d:%02d:%02d.%d", 
            			w.getTimeElapsed() / 3600000, 
            			(w.getTimeElapsed() % 3600000) / 60000,
            			(w.getTimeElapsed() % 60000) / 1000,
            			w.getTimeElapsed() % 1000));
            } else {
            	timeElapsed.setText(String.format("%d:%02d.%d", 
            			(w.getTimeElapsed() % 3600000) / 60000,
            			(w.getTimeElapsed() % 60000) / 1000,
            			w.getTimeElapsed() % 1000));
            }
            
            TextView distance =
            		(TextView)convertView.findViewById(R.id.workoutLogEntryListItem_distView);
            if(w.getDistanceTraveled() <= 0.0) {
            	distance.setText("N/A");
            }
            else if(WorkoutHistoryContainer.useMetricUnits()) {
            	distance.setText(String.format("%1.2f km", w.getDistanceTraveled()));
            } else {
            	distance.setText(String.format("%1.2f miles", w.getDistanceTraveled() * KM_TO_MILES));
            }
            
            TextView speed =
            		(TextView)convertView.findViewById(R.id.workoutLogEntryListItem_speedView);
            if(w.getSpeedAvg() <= 0.0) {
            	speed.setText("N/A");
            }
            else if(WorkoutHistoryContainer.useMetricUnits()) {
            	speed.setText(String.format("%1.2f kph", w.getSpeedAvg()));
            } else {
            	speed.setText(String.format("%1.2f mph", w.getSpeedAvg() * KM_TO_MILES));
            }

            return convertView;
        }
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case android.R.id.home:
    			if(NavUtils.getParentActivityName(getActivity()) != null) {
    				NavUtils.navigateUpFromSameTask(getActivity());
    			}
    			return true;
    		
    		default:
    			return super.onOptionsItemSelected(item); 
    	}
    }

}
